package com.light.mytext.websocket

import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.light.mytext.R
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket


class MyWebSocketActivity : AppCompatActivity() {
    private var client: OkHttpClient? = null
    private var sendTime = 0L

    // 发送心跳包
    private var mHandler: Handler = Handler()

    // 每隔2秒发送一次心跳包，检测连接没有断开
    private val HEART_BEAT_RATE = (2 * 1000).toLong()

    // 发送心跳包
    private val heartBeatRunnable: Runnable = object : Runnable {
        override fun run() {
            if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                val message: String = sendData()
                mSocket!!.send(message)
                sendTime = System.currentTimeMillis()
            }
            if (mHandler != null) {
                mHandler.postDelayed(this, HEART_BEAT_RATE) //每隔一定的时间，对长连接进行一次心跳检测
            }
        }
    }
    private var mSocket: WebSocket? = null
    private var request: Request? = null
    private var listener: EchoWebSocketListener? = null
    /******
     * ws://192.168.56.1:8888/app/common/websocket/{uid}/{venueId}/{type}
     * type 1 收银端  2 大小显  3 电视 4 拼接屏
     * uid 用户id或者设备id
     * venueId 场馆id
     */
    private var weburl="ws://192.168.3.71:8888/app/common/websocket/1392729232608079873/1392297544849584129/2"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_web_socket)
        listener = EchoWebSocketListener {//重连会走这里
            if (mHandler != null) {
                mSocket = client!!.newWebSocket(request, listener)
            }
        }
//        Request request = new Request.Builder().url("ws://echo.websocket.org").build();
        //        Request request = new Request.Builder().url("ws://echo.websocket.org").build();
        request = Request.Builder().url(weburl).build()
        client = OkHttpClient()
        mSocket = client!!.newWebSocket(request, listener)
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE)
    }

    fun sendData(): String {
        var jsonHead = ""
        val mapHead: MutableMap<String, Any> = HashMap()
        mapHead["cmd"] = "wd_heartbeat"
        jsonHead = buildRequestParams(mapHead)
        Log.e("TAG", "sendData: $jsonHead")
        return jsonHead
    }

    fun buildRequestParams(params: Any?): String {
        val gson = Gson()
        return gson.toJson(params)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        mSocket!!.cancel()
        mSocket!!.close(1000, null)
    }

}